// 存储登陆人信息
import { login, getUserInfo, getUserDetailById } from '@/api/user.js'
// 导入持久化存储方法  * as auth 表示导入auth模块中所有方法
import * as auth from '@/utils/auth'
import { resetRouter } from '@/router'

export default {
  // 开启命名空间（模块化）
  namespaced: true,
  // 定义数据变量（和组件data类似）
  state: {
    token: auth.getToken() || '',
    user: {}
  },
  mutations: {
    setToken (state, token) {
      state.token = token
      auth.setToken(token)
    },
    removeToken (state) {
      state.token = ''
      auth.removeToken()
    },
    setUser (state, user) {
      state.user = user
    },
    delUser (state) {
      state.user = {}
    }
  },
  actions: {
    async getTokenAction (ctx, formData) {
      const res = await login(formData)
      ctx.commit('setToken', res)
    },
    async getUserAction ({ commit }) {
      // 获取用户信息
      const user = await getUserInfo()
      // 获取用户头像
      const photo = await getUserDetailById(user.userId)
      // console.log(user)
      commit('setUser', { ...user, ...photo })
      return user.roles
    },
    logoutAction ({ commit }) {
      commit('delUser')
      commit('removeToken')
      // 重置了路由
      resetRouter()
      // 重置左侧菜单栏
      commit('menus/setMenusList', [], { root: true })
    }
  }
}
